#coding:utf-8
from Tkinter import *
import tkMessageBox
import time
import threading
#import stake_serial as ser
import mySerial as ser
#import stake_http as http
import myhttp as http
import sys

class Application(Frame):
	def __init__(self, master=None):
		Frame.__init__(self, master)
		self.pack()
		self.createWidgets()
		self.lockListen = threading.Lock()
		self.bListen = False

	def createWidgets(self):
		#上方标题
		self.LabSend = Label(self, text = '发送信息')
		self.LabSend.grid()

		self.LabRecive = Label(self, text = '接收信息')
		self.LabRecive.grid(row = 0, column = 1)

		#两个list
		self.listSend = Listbox(self, width = 50)
		self.listSend.grid(row = 1, column = 0)

		self.listRecive = Listbox(self, width = 50)
		self.listRecive.grid(row = 1, column = 1)

		#两个按钮
		self.btnStart = Button(self, text='开始', command=self.start)
		self.btnStart.grid(row = 2, column = 0)

		self.btnEnd = Button(self, text='停止', command=self.end, state = DISABLED)
		self.btnEnd.grid(row = 2, column = 1)

	def start(self):
		#更改按钮状态
		self.btnEnd['state'] = ACTIVE
		self.btnStart['state'] = DISABLED

		#创建新的进程及信号量
		self.tListenSer = threading.Thread(target=self.do, name="ListenSerial")

		#修改进程运行标志
		self.lockListen.acquire()
		self.bListen = True
		self.lockListen.release()

		#执行监听进程
		self.tListenSer.start()

	def end(self):
		#修改进程运行标志
		self.lockListen.acquire()
		self.bListen = False
		self.lockListen.release()

		#修改按钮状态
		self.btnEnd['state'] = DISABLED
		self.btnStart['state'] = ACTIVE

	def do(self):
		isStop = True
		while isStop:
			#获取进程运行状态
			self.lockListen.acquire()
			isStop = self.bListen
			self.lockListen.release()
			
			#从串口读取信息
			stu_id = ser.read()

			#未收到消息
			if stu_id is None:
				continue

			#从服务器获取学生信息
			stuInfo = http.getInfo(stu_id)

			#将学生信息写入串口
			ret = ser.write(stuInfo)

			#更新界面
			now_time = time.localtime(time.time())
			self.listRecive.insert(0, "[%s] User %s login" % (time.asctime(now_time), stu_id))
			if len(stuInfo) <= ret:
				self.listSend.insert(0, "[%s] Get User %s Info" % (time.asctime(now_time), stuInfo))
			else:
				self.listSend.insert(0, "[%s] Send Msg Error %s" % (time.asctime(now_time), stuInfo))

			#获取进程运行标志
			self.lockListen.acquire()
			isStop = self.bListen
			self.lockListen.release()
	def myExit(self):
		#修改进程运行标志
		self.lockListen.acquire()
		self.bListen = False
		self.lockListen.release()

		self.master.destroy()
if __name__ == '__main__':
	app = Application()
	# 设置窗口标题:
	app.master.title('Tkinter')
	app.master.protocol("WM_DELETE_WINDOW", app.myExit)
	# 主消息循环:
	app.mainloop()